import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;


/**
 * Code taken from following URL:
 * http://www.artima.com/forums/flat.jsp?forum=1&thread=36883
 * @author Administrator
 *
 */
public class ServerSideSocket {
int port = 0;

	public ServerSideSocket(int p){
		port = p;
	}
	
	public void createSocket(){
		JFrame frame = new JFrame();
		ServerSocket socket = null;
		Socket client = null;
		BufferedReader fromClient = null;
		
		try {
			socket = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try{
			client = socket.accept();
			fromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
			String in = fromClient.readLine();
			StringBuffer temp = new StringBuffer();
			for(int i = 1; i < in.length(); i+=2){
				temp.append(in.charAt(i));
			}
			String pass = temp.toString();
			if(!pass.equals(EasyFTP.privKey)){
				socket.close();
				client.close();
				JOptionPane.showMessageDialog(frame, "Socket creation unsuccessfully:\nIncorrect Passkey");
			}
			else{
				//Open file dialog and send the file chosen
				System.out.println("SendFile");
				SendFile send = new SendFile(socket, client);
				send.makeDialog();
			}
		
		}
		catch (IOException e1){
			e1.printStackTrace();
		}
		
	}
}
